<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">原始单据复核</span>
      </div>
      <s-table
        :table="table"
        :expand="false"
        @http="tableWatch">
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          label="操作"
          width="210">
          <template scope="s">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="dialogOpen2(s.row, 1)" round></el-button>
            <el-button type="success" v-if="s.row.processState === 4" size="mini" @click="employeeReview(s.row)" round>复核</el-button>
            <el-button type="warning" size="mini" @click="dialogSearchOpen(s.row)" round>轨迹</el-button>
            <el-tag type="success" v-if="s.row.processState === 6" class="tag">已复核</el-tag>
            <el-tag type="danger" v-if="s.row.processState === 5" class="tag">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}" class="">
            <el-form-item label="报销类型" prop="reimbursementType">
              <el-select v-model="autoVue_table_reimbursementType" placeholder="报销类型">
                <el-option
                  label="全部"
                  value="">
                </el-option>
                <el-option
                  label="成本费用"
                  value="expenseCost">
                </el-option>
                <el-option
                  label="暂借款"
                  value="borrowing">
                </el-option>
                <el-option
                  label="差旅"
                  value="travelExpense">
                </el-option>
                <el-option
                  label="奖励扣款"
                  value="rewardDeduction">
                </el-option>
                <el-option
                  label="结算单"
                  value="adviceSettlement">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}" class="">
            <el-form-item label="报销单号" prop="reimbursementCode">
              <el-input type="text"
                        class="input"
                        v-model="autoVue_table_reimbursementCode"
                        placeholder="报销单号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}" class="">
            <el-form-item label="报销人员" prop="proposer">
              <el-input type="text"
                        class="input"
                        v-model="autoVue_table_proposer"
                        placeholder="报销人员"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}" class="">
            <el-form-item label="复核状态" prop="processState">
              <el-select v-model="autoVue_table_processState" placeholder="复核状态">
                <el-option
                  label="全部"
                  value="">
                </el-option>
                <el-option
                  label="待复核"
                  :value="4">
                </el-option>
                <el-option
                  label="已复核"
                  :value="6">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 23, offset: 0}" class="">
            <el-form-item label="报销日期" prop="reimbursementDate">
              <el-date-picker
                v-model="autoVue_table_reimbursementDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 23, offset: 0}" class="">
            <el-form-item prop="departmentId" label="所属部门">
              <el-cascader
                :options="DEPARTMENT.department"
                v-model="autoVue_table_departmentId"
                :show-all-levels="false"
                ref="departmentId"
                clearable
                filterable
                change-on-select
                :props="{
                  value: 'key',
                }"
                placeholder="所属部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </s-table>
    </el-card>
    <process ref="process"></process>
    <s-dialog :dialog="dialog" :closeTip="false" :close="dialogInit">
      <div>
        <s-form :form="formDialog" ref="formDialog">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="line-height: 36px; font-size: 20px">{{dialog.card.title}}</span>
              <span class="process">报销编号：{{formDialog.reimbursementCode}}</span>
              <span class="process">当前流程： </span>
              <!--:disabled="dialog.row.processState === 5"-->
              <el-select v-model="formDialog.workflowconfigId"
                         disabled
                         class="process_select"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.process.data"
                  :key="item.value"
                  :label="item.processName + '   ' +  item.departmentName"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-checkbox
                disabled
                class="process"
                v-model="dialog.process.option.default">默认流程</el-checkbox>
              <el-button class="process process_download" size="mini" type="info" @click="download(dialog.card.title)">导入模板下载</el-button>
              <el-button class="process process_download" size="mini" type="primary" @click="download(dialog.card.title)">导入</el-button>
            </div>
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="reimbursementDate" :label="dialog.card.title !== '结算单' ? '报销日期' : '结算日期'">
                  <el-date-picker
                    v-model="formDialog.reimbursementDate"
                    disabled
                    format="yyyy年 MM月 dd日"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}" v-if="dialog.card.title !== '暂借款借支单'">
                <el-form-item prop="reimbursementCode" label="报销部门">
                  <div class="s-content"><el-tag type="success">{{formDialog.departmentName}}</el-tag>
                    <el-button type="primary" style="float: right" v-if="dialog.card.title === '差旅费用报销单' && dialog.type !== 1" @click.prevent="addTravelUser">添加出差人员</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="dialog.card.title === '差旅费用报销单'">
              <el-row
                :key="index"
                v-for="(item, index) in formDialog.travel">
                <el-col :xs="24" :lg="{span: dialog.type === 1 ? 11 : 9, offset: 0}">
                  <el-form-item
                    :prop="'travel.' + index + '.user'"
                    :label="'出差人员 ' + (index + 1)"
                    :rules="{required: true, message: '出差人员不能为空', trigger: 'blur'}">
                    <el-input
                      type="text"
                      v-model="item.user"
                      placeholder="出差人员"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: dialog.type === 1 ? 11 : 9, offset: 1}">
                  <el-form-item :prop="'travel.' + index + '.level'"
                                :label="'职位等级 ' + (index + 1)"
                                :rules="{required: true, message: '职位等级不能为空', trigger: 'blur'}">
                    <el-input
                      type="text"
                      v-model="item.level"
                      :placeholder="`出差人员 ${(index + 1)} 的职位等级`"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 3, offset: 1}" v-if="dialog.type !== 1">
                  <el-form-item label="可用操作">
                    <div class="s-content">
                      <el-button
                        size="mini"
                        icon="el-icon-delete"
                        round
                        type="danger"
                        @click.prevent="removeTravelUser(item)">删除</el-button>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="attributionDate" label="归属期间">
                    <el-date-picker
                      v-model="formDialog.attributionDate"
                      :clearable="false"
                      type="month"
                      placeholder="归属周期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="travelReason" label="出差事由">
                    <el-input
                      type="text"
                      v-model="formDialog.travelReason"
                      placeholder="出差事由"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-if="dialog.card.title === '暂借款借支单'">
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="borrower" label="借款人 ">
                    <div class="s-content">
                      {{dialog.row.proposer}}
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item label="所属部门">
                    <div class="s-content">{{dialog.row.departmentName}}</div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="loanProject" label="借款项目  ">
                    <el-input
                      type="text"
                      v-model="formDialog.loanProject"
                      placeholder="借款项目  "></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="loanMoney" label="借款金额 ">
                    <el-input
                      type="text"
                      v-model="formDialog.loanMoney"
                      placeholder="借款金额 "></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :lg="{span: 11, offset: 0}">
                  <el-form-item prop="repaymentDate" label="还款时间  ">
                    <el-date-picker
                      v-model="formDialog.repaymentDate"
                      type="date"
                      :editable="false"
                      placeholder="还款时间"
                      :picker-options="pickerOptions">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 11, offset: 1}">
                  <el-form-item prop="loanMoneyCap" label="借款金额(大写) ">
                    <div class="s-content">
                      {{formDialog.loanMoneyCap}}
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-collapse :value="['1', '2', '3', '4']" class="__rbApply">
              <el-collapse-item :title="dialog.card.title === '结算单' ? '结算明细 (提示： 按住 shift  使用 鼠标滑轮 控制横向滚动页面)' : '报销明细'" name="1" v-if="dialog.card.title !== '暂借款借支单'">
                <expense :init="dialog.details" :search="dialog.type === 1" v-if="dialog.card.title === '成本费用报销单'" ref="details" @change="handleDetailsChange"></expense>
                <travel :init="dialog.details" :search="dialog.type === 1" v-if="dialog.card.title === '差旅费用报销单'" ref="details" @change="handleDetailsChange2"></travel>
                <rewardDeduction :init="dialog.details" :search="dialog.type === 1" v-if="dialog.card.title === '奖励扣款报销单'" ref="details" @change="handleDetailsChange3"></rewardDeduction>
                <adviceSettlement :init="dialog.details" :search="dialog.type === 1" v-if="dialog.card.title === '结算单'" ref="details" @change="handleDetailsChange4"></adviceSettlement>
              </el-collapse-item>
              <el-row class="other" v-if="dialog.card.title !== '暂借款借支单' && dialog.card.title !== '结算单'">
                <el-col :xs="24" :lg="{span: 4, offset: 0}" v-if="dialog.card.title === '成本费用报销单'">
                  <el-form-item prop="isWithholding" label="是否预提">
                    <el-switch
                      v-model="formDialog.isWithholding"
                      :disabled="dialog.type === 1"
                      active-text="是"
                      :active-value="2"
                      :inactive-value="1"
                      inactive-text="否"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: dialog.card.title === '成本费用报销单' ? 1 : 0}">
                  <el-form-item label="报销金额合计">
                    {{SplitK(formDialog.money)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 8, offset: 1}">
                  <el-form-item pr label="核实金额（大写）">
                    {{formDialog.moneyCap}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}" v-if="formDialog.borrowingMoney !== -1">
                  <el-form-item label="借款金额合计">
                    {{SplitK(formDialog.borrowingMoney)}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="other" v-if="dialog.card.title === '结算单'">
                <el-col :xs="24" :lg="{span: 4, offset: 0}">
                  <el-form-item label="报销金额合计">
                    {{SplitK(formDialog.money)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 8, offset: 1}">
                  <el-form-item label="核实金额（大写）">
                    {{formDialog.moneyCap}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}">
                  <el-form-item label="油卡金额">
                    {{SplitK(formDialog.moneyYouKa)}}
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :lg="{span: 4, offset: 1}">
                  <el-form-item label="现金金额">
                    {{SplitK(formDialog.moneyXianJin)}}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-collapse-item title="收款方" name="4" v-if="dialog.card.title === '差旅费用报销单' || dialog.card.title === '暂借款借支单'">
                <payee ref="payee" :card="dialog.card" :init="dialog.payee" :travel="dialog.card.title === '差旅费用报销单'"></payee>
              </el-collapse-item>
              <el-collapse-item title="附件列表" name="2">
                <el-upload
                  :disabled="dialog.type === 1"
                  :action="action"
                  :multiple="true"
                  name="reimbursement_image"
                  list-type="picture-card"
                  :file-list="dialog.fileVoList"
                  :before-upload="dialogUploadBefore"
                  ref="upload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <p>附件数量：  {{$refs.upload ? $refs.upload.uploadFiles.length : 0}}</p>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </s-form>
      </div>
      <el-button type="primary"
                 slot="footer"
                 v-if="dialog.row.state !== 1 && dialog.type === 1 && (dialog.row.processState === 1 || dialog.row.processState === 5)"
                 @click="dialogUploadOpen(dialog.row)">直接提交</el-button>
      <el-button slot="footer" v-if="dialog.type !== 1" @click="dialogSave">保存草稿</el-button>
      <el-button slot="footer" type="primary" v-if="dialog.type !== 1" @click="dialogSave(1)">直接提交</el-button>
    </s-dialog>
    <v-viewer :options="viewer.option" :images="viewer.images"
              @inited="viewerInit" ref="viewer">
      <template scope="scope">
        <ul id="viewer">
          <li v-for="image in scope.images" :key="image">
            <img :src="image"/>
          </li>
        </ul>
      </template>
    </v-viewer>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise, SplitK, IsImage, DownFile} from '~/plugins/Tools';
  import Config from '~/config';
  import Expense from '~/components/reimbursement/expense.vue';
  import Travel from '~/components/reimbursement/travel.vue';
  import Department from '~/components/reimbursement/department.vue';
  import Payee from '~/components/reimbursement/payee.vue';
  import RewardDeduction from '~/components/reimbursement/rewardDeduction.vue';
  import AdviceSettlement from '~/components/reimbursement/adviceSettlement.vue';
  import Nzh from 'nzh';
  let {
    PublicImageServer,
  } = Config;
  function __cards () {
    return [
      {
        title: '成本费用报销单',
        code: 'expenseCost',
        body: 'test',
        img: 'apple',
      },
      {
        title: '差旅费用报销单',
        code: 'travelExpense',
        body: 'test',
        img: 'apple',
      },
      {
        title: '暂借款借支单',
        code: 'borrowing',
        body: 'test',
        img: 'apple',
      },
      {
        title: '结算单',
        code: 'adviceSettlement',
        body: 'test',
        img: 'apple',
      },
      {
        title: '奖励扣款报销单',
        code: 'rewardDeduction',
        body: 'test',
        img: 'apple',
      },
    ];
  }
  function __formDialog () {
    return {
      reimbursementDate: { value: new Date(), rule: [ 'vNull' ], type: 'Date' },
      departmentId: { value: '', rule: [ 'vNull' ] },
      departmentName: { value: '', rule: [] },
      reimbursementCode: { value: '', rule: [ 'vNull' ] },
      money: { value: 0, rule: [ 'vNull', 'vNumber' ] },
      moneyYouKa: { value: '', rule: [] },
      moneyXianJin: { value: '', rule: [] },
      moneyCap: { value: Nzh.cn.toMoney(0), rule: [ 'vNull' ] },
      borrowingMoney: { value: 0, rule: [ 'vNull', 'vNumber' ] },
      enclosureNum: { value: 0, rule: [ 'vNumber' ] },
      workflowconfigId: { value: '', rule: [ 'vNull' ] },
      isWithholding: { value: 1, rule: [ 'vNull' ] },
      fileVoList: { value: '', rule: [] },

      ...__formDialog_travel(),
      ...__formDialog_borrowing(),
    };
  }
  function __formDialog_travel () {
    return {
      travel: {
        value: [
          {
            user: '',
            level: '',
          },
        ],
        rule: [] },
      travelUsers: {value: '', rule: ['vNull']},
      positionLeave: {value: '', rule: ['vNull']},
      attributionDate: {value: '', rule: ['vNull__change'], type: 'Date'},
      travelReason: {value: '', rule: ['vNull']},
    };
  }
  function __formDialog_borrowing () {
    return {
      departmentId: { value: '', rule: [ 'vNull' ] },
      borrower: { value: '', rule: ['vNull__change'] },
      loanMoney: { value: '', rule: ['vNull', 'vNumber'] },
      loanProject: { value: '', rule: ['vNull'] },
      loanMoneyCap: { value: '', rule: [] },
      repaymentDate: { value: '', rule: [], type: 'Date' },
    };
  }

  export default AutoVue({
    data: {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now() + 15 * 24 * 60 * 60 * 1000 || time.getTime() < Date.now();
        },
      },
      dialog: {
        title: '新增',
        fullscreen: true,
        width: '100%',
        card: {},
        reimbursementUser: [],
        borrower: [],
        process: {
          data: [],
          option: {
            active: '',
            default: true,
          },
        },

        row: {},
        type: 0,

        details: [],
        payee: [],
        department: [],
        fileVoList: [],
      },
      formDialog: __formDialog(),
      dialogUpload: {
        userId: [],
      },
      cards: __cards(),
      dialogImage: {
        url: false,
        fullscreen: true,
        formRef: false,
        width: '100%',
      },
      viewer: {
        option: {
          zIndex: 100000,
        },
        el: {},
        images: [],
      },

      table: {
        column: [
          {'label': '报销日期', 'prop': 'reimbursementDate', type: 'DateRange', search: true, 'minWidth': '120px'},
          {'label': '报销人员', 'prop': 'proposer', search: true, 'minWidth': '0px'}, {
            'label': '报销部门',
            'prop': 'departmentName',
            search: true,
            searchName: 'departmentId',
            searchAfter: function (value) {
              return value.reverse()[0];
            },
            searchInitValue: function () {
              return [];
            },
            type: 'custom',
            'minWidth': '200px',
          }, {'label': '报销单号', search: true, 'prop': 'reimbursementCode', 'minWidth': '210px'}, {
            'label': '金额合计',
            'prop': 'money',
            formatter: (row, column) => {
              return SplitK(row[column.property || column]);
            },
            search: true,
            searchName: 'processState',
            'minWidth': '0px',
          },
          {'label': '报销类型', search: true, searchName: 'reimbursementType', 'prop': 'reimbursementTypeName', 'minWidth': '0px'},
          {'label': '附件数量', 'prop': 'enclosureNum', 'minWidth': '0px'},
        ],
        popover: {
          width: '660px',
        },
        key: 'id',
        url: '/reimbursement/seachReviewPage',
        muti: false,
      },
    },
    computed: {
      action: function () {
        return PublicImageServer.src + '/file/upload/image/reimbursement';
      },
      server: function () {
        return PublicImageServer.src + '/image/reimbursement/';
      },
    },
    beforeRouteLeave (to, from, next) {
      this.$destroy();
      next();
    },
    transition: 'slide-fade-bottom',
    head: {
      'title': '原始单据复核',
      'meta': [
        {'hid': 'description', 'name': 'description', 'content': '乐速科技平台 报销单管理 原始单据复核'},
      ],
    },
    store: ['USER', 'TRAVEL_moneyUse', 'TRAVEL_moneyUse2', 'TRAVEL_moneySum', 'DEPARTMENT'],
    components: {
      'expense': Expense,
      'travel': Travel,
      'department': Department,
      'payee': Payee,
      'rewardDeduction': RewardDeduction,
      'adviceSettlement': AdviceSettlement,
    },
    props: {
      init: {
        type: Array,
      },
    },
    methods: {
      SplitK,
      employeeReview (row) {
        this.$confirm('您将复核报销单。', '确认复核？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          await this.get('/reimbursement/toReview/' + row.id);
          this.tableWatch('table');
        });
      },

      tableDelete (row) {
        this.$confirm('您将删除此报销单。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          await this.get('/reimbursement/blankOut/' + row.id);
          this.tableWatch('table');
        });
      },
      viewerInit (viewer) {
        this.viewer.el = viewer;
      },
      viewerShow () {
        this.$viewer.show();
      },
      download () {
        this.$alert('现在没有接口！', '提示');
      },

      async handleRemove (file) {
        try {
          await this.p(this.action + '/' + file.response.filename, {
            method: 'delete',
            headers: {
              sLoading: true,
            },
          });
        } catch (err) {
          console.error(err);
        }
      },
      handleDetailsChange (data) {
        let money = 0;
        let borrowingMoney = 0;
        data.forEach(item => {
          money += item.money || 0;
          borrowingMoney += item.loanNum || 0;
        });
        this.formDialog.money = money;
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = borrowingMoney;
        return this.formDialog.money;
      },
      handleDetailsChange2 (data, type) {
        let money = 0;
        data.forEach(item => {
          money += parseFloat(item.trafficMoney) + parseFloat(item.travelMoney) + parseFloat(item.otherMoney);
        });
        this.formDialog.money = money;
        this.SET('TRAVEL_moneySum', money);
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      handleDetailsChange3 (data) {
        let money = 0;
        data.forEach(item => {
          money += parseFloat(item.money);
        });
        this.formDialog.money = money;
        this.SET('TRAVEL_moneySum', money);
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      handleDetailsChange4 (data) {
        let money = 0;
        let moneyYouKa = 0;
        let moneyXianJin = 0;
        data.forEach(item => {
          money += parseFloat(item.oilcardSettleAmout) + parseFloat(item.cashAmout);
          moneyYouKa += parseFloat(item.oilcardSettleAmout);
          moneyXianJin += parseFloat(item.cashAmout);
        });
        this.formDialog.money = money;
        this.formDialog.moneyYouKa = moneyYouKa;
        this.formDialog.moneyXianJin = moneyXianJin;
        this.SET('TRAVEL_moneySum', money);
        this.formDialog.moneyCap = Nzh.cn.toMoney(money);
        this.formDialog.borrowingMoney = -1;
        return this.formDialog.money;
      },
      async dialogBorrower (query) {
        let {contentList} = await this.post('/empolyee/searchByPage', {
          bxSetlecycleName: query,
          'pageNumber': 1,
          'pageSize': 20,
        });
        this.dialog.borrower = contentList;
      },
      dialogBorrowerChange (id) {
        this.dialog.borrower.forEach(item => {
          if (item.id === id) {
            this.formDialog.departmentId = item.bxSupplierDepartmentid;
            this.formDialog.departmentName = item.bxSupplierDepartmentname;
          }
        });
      },

      dialogInit (type) {
        switch (this.dialog.card.title) {
        case '成本费用报销单':
          this.$refs.details.tableClear('table');
          this.$refs.details.loanNum = {};
          break;
        case '差旅费用报销单':
          this.DEL('TRAVEL_money');
          this.$refs.details.sTable.data = [];
          this.$refs.payee.tableClear('table');
          break;
        case '暂借款借支单':
          this.DEL('TRAVEL_money');
          this.$refs.payee.tableClear('table');
          break;
        case '结算单':
          this.$refs.details.sTable.data = [];
          this.$refs.details.sTable.old = [];
          break;
        case '奖励扣款报销单':
          this.DEL('TRAVEL_money');
          this.$refs.details.tableClear('table');
          break;
        }
        this.$refs.upload.uploadFiles = [];
        this.dialog.dialogInit.call(this);
      },
      async dialogOpen (card, row, type) {
        this.dialog.type = type;
        this.dialog.visible = true;
        if (row.borrowingVoList) {
          row = {
            ...row,
            ...row.borrowingVoList,
          };
        }
        this.dialog.row = row;
        this.$nextTick(() => {
          this.formDialog = {
            ...this.formDialog,
            ...this.ObjectClone(__formDialog(), row),
          };
          this.formDialog.attributionDate = new Date(row.attributionDate);
          if (card.title === '差旅费用报销单') {
            let travelUsers = row.travelUsers.split(';');
            let positionLeave = row.positionLeave.split(';');
            let travel = [];
            travelUsers.forEach((item, index) => {
              travel.push({
                user: item,
                level: positionLeave[index],
              });
            });
            travel.pop();
            this.$set(this.formDialog, 'travel', travel);
          }
        });
        let autoPromise = [
          async () => {
            let {contentList} = await this.post('/workflowConfig/selectWorkflow', {
              'processType': card.code,
            });
            this.dialog.process.data = contentList;
            // this.formDialog.workflowconfigId = contentList[0] ? contentList[0].id : '';
          },
        ];
        let files = [];
        switch (card.title) {
        case '成本费用报销单':
          this.dialog.details = row.expenseCostFormDetailVoList;
          files = [];
          row.fileVoList.forEach(item => {
            files.push({
              name: item.fileUrl,
              url: PublicImageServer.src + '/image/reimbursement/' + item.fileUrl,
              response: {
                filename: item.fileUrl,
              },
              status: 'finished',
            });
          });
          this.dialog.fileVoList = files;
          break;
        case '差旅费用报销单':
          autoPromise.push(async () => {
            this.reimbursementUser(this.USER.user.name);
          });
          let {
            travelExpensesFormDetailVoList,
            payeeList,
            fileVoList,
          } = row;
          this.dialog.details = travelExpensesFormDetailVoList;
          this.dialog.payee = payeeList;
          files = [];
          fileVoList.forEach(item => {
            files.push({
              name: item.fileUrl,
              url: PublicImageServer.src + '/image/reimbursement/' + item.fileUrl,
              response: {
                filename: item.fileUrl,
              },
              status: 'finished',
            });
          });
          this.dialog.fileVoList = files;
          break;
        case '暂借款借支单':
          this.dialog.payee = row.payeeList;
          autoPromise.push(async () => {
            this.dialogBorrower(row.borrower);
          });
          files = [];
          row.fileVoList.forEach(item => {
            files.push({
              name: item.fileUrl,
              url: PublicImageServer.src + '/image/reimbursement/' + item.fileUrl,
              response: {
                filename: item.fileUrl,
              },
              status: 'finished',
            });
          });
          this.dialog.fileVoList = files;
          break;
        case '结算单':
          this.dialog.details = row.settlementInfoVoList;
          files = [];
          row.fileVoList.forEach(item => {
            files.push({
              name: item.fileUrl,
              url: PublicImageServer.src + '/image/reimbursement/' + item.fileUrl,
              response: {
                filename: item.fileUrl,
              },
              status: 'finished',
            });
          });
          this.dialog.fileVoList = files;
          break;
        case '奖励扣款报销单':
          this.dialog.details = row.rewardDeductionVoList;
          files = [];
          row.fileVoList.forEach(item => {
            files.push({
              name: item.fileUrl,
              url: PublicImageServer.src + '/image/reimbursement/' + item.fileUrl,
              response: {
                filename: item.fileUrl,
              },
              status: 'finished',
            });
          });
          this.dialog.fileVoList = files;
          break;
        }
        await AutoPromise(autoPromise);
        this.dialog.card = card;
      },
      async reimbursementUser (query = '') {
        let {contentList} = await this.post('/empolyee/searchByPage', {
          bxSetlecycleName: query,
          'pageNumber': 1,
          'pageSize': 20});
        this.dialog.reimbursementUser = contentList;
      },
      handlePictureCardPreview (file) {
        if (IsImage(file.name)) {
          let images = [];
          let index = 0;
          let length = 0;
          this.$refs.upload.uploadFiles.forEach((item, i) => {
            if (IsImage(item.name)) {
              images.push(item.url);
              if (file.response.filename === item.response.filename) {
                index = length;
              }
              length++;
            }
          });
          this.viewer.images = images;
          setTimeout(() => {
            this.viewer.el.index = index;
            this.viewer.el.view(index);
            this.viewer.el.show();
          }, 250);
        } else {
          DownFile(this.server + file.response.filename, file.response.filename);
        }
      },
      dialogSave (flag) {
        if (flag !== 1) {
          flag = 2;
        }
        if (flag === 1) {
          if (this.dialog.card.title !== '结算单' ? (typeof this.$refs.upload !== 'undefined' && this.$refs.upload.uploadFiles.length > 0) : true) {
            if (this.formDialog.money || this.dialog.card.title === '暂借款借支单') {
              this.VALIDATE('formDialog', option => OPTION.call(this, option));
            } else {
              this.$alert('报销金额为0元 没有意义！', '没有明细');
            }
          } else {
            this.$alert('必须上传附件！', '没有附件');
          }
        } else {
          OPTION.call(this, this.FORMOPTION('formDialog'));
        }
        async function OPTION (option) {
          if (option.borrowingMoney === -1) {
            delete option.borrowingMoney;
          }
          option.enclosureNum = this.$refs.upload.uploadFiles.length;
          let fileVoList = [];
          this.$refs.upload.uploadFiles.forEach(item => {
            fileVoList.push({fileUrl: item.response.filename});
          });
          let step = {};
          switch (this.dialog.card.title) {
          case '成本费用报销单':
            step = {
              reimbursementType: 'expenseCost',
              ...option,
              expenseCostFormDetailVoList: this.$refs.details.table.data,
              fileVoList,
            };
            break;
          case '差旅费用报销单':
            if (this.TRAVEL_moneyUse !== this.TRAVEL_moneySum) {
              return this.$alert('剩余金额为： ' + SplitK(this.TRAVEL_moneySum - this.TRAVEL_moneyUse) + ' 元', '收款金额合计不足');
            }
            option.travelUsers = '';
            option.positionLeave = '';
            option.travel.forEach(item => {
              option.travelUsers += item.user + ';';
              option.positionLeave += item.level + ';';
            });
            delete option.travel;
            step = {
              reimbursementType: 'travelExpense',
              ...option,
              travelExpensesFormDetailVoList: this.$refs.details.sTable.data,
              payeeList: this.$refs.payee.table.data,
              fileVoList,
            };
            break;
          case '暂借款借支单':
            /*
            step = {
              reimbursementType: 'borrowing',
              ...option,
              money: option.loanMoney,
              moneyCap: option.loanMoneyCap,
              borrowingVoList: this.ObjectClone(__formDialog_borrowing(), option),
              payeeList: this.$refs.payee.table.data,
              fileVoList,
            };
            */
            break;
          case '奖励扣款报销单':
            step = {
              reimbursementType: 'rewardDeduction',
              ...option,
              rewardDeductionVoList: this.$refs.details.table.data,
              fileVoList,
            };
            break;
          case '结算单':
            step = {
              reimbursementType: 'adviceSettlement',
              ...option,
              settlementInfoVoList: this.$refs.details.sTable.old,
              fileVoList,
            };
            this.dialogInit(1);
            break;
          }
          if (flag === 1) {
            step.id = this.dialog.row.id;
            await this.put('/reimbursement', step);
            this.formDialogUpload.id = this.dialog.row.id;
            this.dialogUploadOpen();
          } else if (flag === 2) {
            step.id = this.dialog.row.id;
            await this.put('/reimbursement', step);
            this.tableWatch('table');
          }
          this.dialogInit(1);
        }
      },
      dialogUploadBefore (file) {
        const isLt = file.size / 1024 / 1024 < 1;
        if (!isLt) {
          this.$message.error('上传附件大小不能大于 1MB!');
        }
        return isLt;
      },
      removeTravelUser (item) {
        if (this.formDialog.travel.length === 1) {
          return this.$alert('最少一位出差人员！', '提示');
        }
        let index = this.formDialog.travel.indexOf(item);
        if (index !== -1) {
          this.formDialog.travel.splice(index, 1);
        }
      },
      addTravelUser () {
        this.formDialog.travel.push({
          user: '',
          level: '',
        });
      },

      async dialogOpen2 (row, type) {
        let cards = __cards();
        let card = cards.find(item => {
          return item.code === row.reimbursementType;
        });
        let json = await this.get('/reimbursement/getReimbursementById/' + row.id);
        if (card) {
          this.dialogOpen(card, json, type);
        } else {
          this.$alert('对应的 报销单类型 没有找到！', '提示');
        }
      },
      dialogSearchOpen (row) {
        this.$refs.process.open(row);
      },
    },
    mounted: function () {
      this.tableWatch('table');
      this.USE('DEPARTMENT');
      console.log(this);
    },
  });
  /**
   * 报销主表
   reimbursementDate  (string, optional): 报销日期$$$true$false$false$$1$vNull$false,
   departmentId  (string, optional): 报销部门$$$true$false$false$$2$vNull$false,
   reimbursementCode  (string, optional): 报销编号$$$true$false$false$$3$vNull$false,
   money  (string, optional): 报销金额合计$$$true$false$false$$4$vNull,vNumber$false,
   moneyCap  (string, optional): 核实金额（大写）$$$true$false$false$$5$vNull$false,
   borrowingMoney  (string, optional): 借款金额合计$$$true$false$false$$6$vNull,vNumber$false,
   enclosureNum  (string, optional): 附件数量$$$true$false$false$$7$vNumber$false,
   fileVoList  (string, optional): 附件列表$$$true$false$false$$8$$false,
   workflowConfigId  (string, optional): 所属流程$$$true$false$false$$9$$false,
   */
</script>

<style lang="scss">
  .process {
    margin-left: 15px;
  }


  .process_select {
    width: 400px!important;
    @media screen and (max-width: 800px) {
      width: auto!important;
    }
  }

  .process_download {
    margin-top: 10px;
    float: right;
  }

  .__rbApply {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-collapse-item__content {
      padding-bottom: 5px;
    }
  }
</style>
